﻿@{
    if (!WebSecurity.IsAuthenticated)
    {
        string currentUrl = Request.Url.ToString();
        Response.Redirect("~/Account/Login?sender=" + currentUrl);
    }
    
    Layout = "~/Shared/Layouts/_Layout.cshtml";
    Page.Title = "Плаќање";
    
    var address1 = "";
    var address2 = "";
    var town = "";
    var region = "";
    var postalCode = "";
    var country = "";
    
    // Redirect to cart.cshtml if no cart exists in Session
    if (Session["cart"] == null)
    {
        Response.Redirect("Cart");
    }
    
    // Get current cart from Session
    Cart cart = (Cart)Session["cart"];
    
    // Redirect to cart.cshtml if cart has no items
    if(cart.Items.Count() == 0)
    {
        Response.Redirect("Cart");
    }
    
    if (IsPost)
    {
        address1 = Request["address1"];
        address2 = Request["address2"];
        town = Request["town"];
        region = Request["region"];
        postalCode = Request["postalCode"];
        country = Request["country"];
        
        // Validate Delivery Details
        if (address1.IsEmpty()) {
            ModelState.AddError("address1", "Адреса 1 е потребна.");
        }
        
        if (town.IsEmpty()) {
            ModelState.AddError("town", "Град е потребен.");
        }
        
        if (region.IsEmpty()) {
            ModelState.AddError("region", "Регион е потребен.");
        }
        
        if(ModelState.IsValid)
        {        
            // Save Order
            var UserID = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
            
            var db = Database.Open("VirtualeShop");
            var orderSql = "INSERT INTO Orders (UserId, OrderShipped, OrderTotal, " + 
                            "OrderDateTime, Address1, Address2, Town, " + 
                            "Region, PostalCode, Country) " + 
                            "VALUES ( @0, @1, @2, @3, @4, @5, @6, @7, @8, @9 )";
            db.Execute(orderSql,
                        UserID,
                        false,
                        cart.TotalValue,
                        DateTime.Now,
                        address1,
                        address2,
                        town,
                        region,
                        postalCode,
                        country);
            
            var OrderId = db.GetLastInsertId();
            
            foreach(var item in cart.Items)
            {
                orderSql = "INSERT INTO OrderItems (OrderID, ProductID, Size, Price) VALUES (" +
                            "@0, @1, @2, @3)";
                db.Execute(orderSql, OrderId, item.ProductID, item.Size, item.Price);
            }
            
            // Send confirmation email
            WebMail.Send(to: WebSecurity.CurrentUserName,
                subject: "VirtualeShop Потврда на нарачка",
                body: "Вашата нарачка ќе биде испорачана наскоро, " + 
                "пристигнување од 3-5 работни дена. "
            );
            
            // Clear shopping cart
            cart.Clear();
            
            Response.Redirect("OrderComplete");
        }
    }

}

<h1>Плаќање</h1>
<div id="checkout">
    <h2>Детали на нарачка</h2>
    <table id="cartTable">
        <tr>
            <th class="product">Производ</th>
            <th class="size">Големина</th>
            <th class="price">Цена</th>
        </tr>
        
        @foreach (var item in cart.Items)
        {
            <tr>
                <td class="product">@Products.GetProductNameFromId(item.ProductID)</td>
                <td class="size">@item.Size</td>
                <td class="price">£@item.Price</td>
            </tr>
        }
        
        <tr class="cartTotal">
            <td colspan="2">&nbsp;</td>
            <td>Вкупно: £@cart.TotalValue</td>
        </tr>
    </table>
        
    <h2>Детали за испорака</h2>    
    <form action="Checkout" method="post">
        <p>
            @Html.Label("Адреса 1: ", "address1")
            @Html.TextBox("address1", address1, new { maxlength = "100" } )
            @Html.ValidationMessage("address1")
        </p>
        <p>
            @Html.Label("Адреса 2:", address2)
            @Html.TextBox("address2", address2, new { maxlength = "100" } )
        </p>
        <p>
            @Html.Label("Град: ", "town")
            @Html.TextBox("town", town, new { maxlength = "50" } )
            @Html.ValidationMessage("town")
        </p>
        <p>
            @Html.Label("Регион: ", "region")
            @Html.TextBox("region", region, new { maxlength = "50" } )
            @Html.ValidationMessage("region")
        </p>
        <p>
            @Html.Label("Поштенски код: ", "postalCode")
            @Html.TextBox("postalCode", postalCode, new { maxlength = "20" } )
        </p>
        <p>
            @Html.Label("Држава: ", "country")
            @Html.TextBox("country", country, new { maxlength = "50" } )
        </p>
        
        <h2>Потврди нарачка</h2>
        <p>
            <input type="submit" value="Нарачај"/>
        </p>
    </form>
</div>
 